﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace SRM.Core.Utility
{
    public class SecurityHelper
    {
        public static String GetMd5String(String source)
        {
            MD5 md = MD5CryptoServiceProvider.Create();
            byte[] hash;

            //创建Asciencoding的新实例
            //将字符串转换为Unicode字节数组。
            UTF8Encoding enc = new UTF8Encoding();
            byte[] buffer = enc.GetBytes(source);

            hash = md.ComputeHash(buffer);

            StringBuilder sb = new StringBuilder();
            foreach (byte b in hash)
                sb.Append(b.ToString("X2"));
            return sb.ToString();
        }

        public static string GeneratePassword(int strLength)
        {
            char[] constant = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
            System.Text.StringBuilder newRandom = new System.Text.StringBuilder(33);
            Random rd = new Random();
            for (int i = 0; i < strLength; i++)
            {
                newRandom.Append(constant[rd.Next(33)]);
            }
            return newRandom.ToString();
        }

        public static string MD5_Hash(string str_md5_in)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] bytes_md5_in = UTF8Encoding.Default.GetBytes(str_md5_in);
            byte[] bytes_md5_out = md5.ComputeHash(bytes_md5_in);
            string str_md5_out = BitConverter.ToString(bytes_md5_out);
            str_md5_out = str_md5_out.Replace("-", "");
            return str_md5_out;
        }

        public static string SHA1_Hash(string str_sha1_in)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] bytes_sha1_in = UTF8Encoding.Default.GetBytes(str_sha1_in);
            byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
            string str_sha1_out = BitConverter.ToString(bytes_sha1_out);
            str_sha1_out = str_sha1_out.Replace("-", "");
            return str_sha1_out.ToLower();
        }
    }
}
